<template>
  <div class="register">
    <div class="simple-title">
      <span>{{ hexAddress }}</span>
      <el-divider></el-divider>
    </div>
    <el-form label-width="auto" :model="longRegister" @submit.native.prevent="">
      <el-form-item label="Long AB CD:" class="form-item">
        <el-input v-model.number="longRegister.longABCD">
          <template #append>
            <span>({{ getLongHex(longRegister.longABCD) }})</span>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="Long CD AB:" class="form-item">
        <el-input v-model.number="longRegister.longCDAB">
          <template #append>
            <span>({{ getLongHex(longRegister.longCDAB) }})</span>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="Long BA DC:" class="form-item">
        <el-input v-model="longRegister.longBADC">
          <template #append>
            <span>({{ getLongHex(longRegister.longBADC) }})</span>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="Long DC BA:" class="form-item">
        <el-input v-model="longRegister.longDCBA">
          <template #append>
            <span>({{ getLongHex(longRegister.longDCBA) }})</span>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup name="LongRegister" lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import {type LongPointRegister } from "@/types/register";
// import { editPointData } from "@/api/deviceApi";
import 'element-plus/dist/index.css'
import { TableHeader } from "@/types/device";
import { useRegisterStore } from "@/stores/register";
const registerStore = useRegisterStore();

const getLongHex = (value:number) =>{
  const buffer = new ArrayBuffer(4);
  const view = new DataView(buffer);
  view.setUint32(0, value, false); // 大端序写入
  const hex = view.getUint32(0, false) // 保持大端序读取
    .toString(16)
    .toUpperCase()
    .padStart(8, '0');
  return "0x" + hex;
}

const props = defineProps({
  registers: { type: Object, required: true },
  isDualRegister: { type: Boolean, required: true },
});

// 核心地址转换逻辑
const hexAddress = computed(() => {
  if (!props.isDualRegister) {
    // 单寄存器处理（完全匹配图片示例）
    const addr = props.registers[TableHeader.Address];
    return registerStore.formatHex(addr);
  } else {
    // 双寄存器处理（用"-"连接）
    if (!Array.isArray(props.registers)) {
      console.error('Dual decode_register mode requires array input');
      return '';
    }
    //按地址升序排列后再连接
    const sortedRegisters = [...props.registers].sort((a, b) =>
      a[TableHeader.Address] - b[TableHeader.Address]
    );
    return sortedRegisters
      .map(reg => registerStore.formatHex(reg[TableHeader.Address]))
      .join('-');
  }
});

const longRegister = ref<LongPointRegister>({
  longABCD: 0,
  longCDAB: 0,
  longBADC: 0,
  longDCBA: 0,
  value: 0,
});

function updateFromValue(value: number) {
  // 计算原始寄存器值（应用乘法和加法系数）
  const registerValue = value;

  // 检查32位数值范围（兼容有符号和无符号）
  if (registerValue < -2147483648 || registerValue > 4294967295) {
    return;
  }

  // 转换为32位无符号表示
  const unsigned32 = registerValue | 0;


  // 生成四种排列组合（模拟不同字节序）
  longRegister.value = {
    longABCD: unsigned32,
    longCDAB: ((unsigned32 & 0xFFFF0000) >>> 16) | ((unsigned32 & 0x0000FFFF) << 16),
    longBADC: ((unsigned32 & 0xFF00FF00) >>> 8) | ((unsigned32 & 0x00FF00FF) << 8),
    longDCBA: (
      ((unsigned32 & 0xFF000000) >>> 24) |
      ((unsigned32 & 0x00FF0000) >>> 8) |
      ((unsigned32 & 0x0000FF00) << 8) |
      ((unsigned32 & 0x000000FF) << 24)
    ),
    value: value,
  }
}

const setLongRegisterValue = (registers: any)=>{
  const value1 = props.registers[0][TableHeader.RegisterValue] || 0; // 十进制值
  const value2 = props.registers[1][TableHeader.RegisterValue] || 0;

  // 1. 将十进制值转为十六进制字符串（补零到4位，如 "000A"）
  const hex1 = value1.toString(16).padStart(4, '0'); // 假设每个值占2字节（4位十六进制）
  const hex2 = value2.toString(16).padStart(4, '0');

  // 2. 拼接为完整的十六进制字符串（如 "000A003B"）
  const combinedHex = hex1 + hex2;

  // 3. 将十六进制字符串转为十进制整数
  longRegister.value.value = parseInt(combinedHex, 16);
}

watch (() => props.registers, (newVal, oldVal) => {
  setLongRegisterValue(newVal);
  updateFromValue(longRegister.value.value);
});

onMounted(() => {
  setLongRegisterValue(props.registers);
  updateFromValue(longRegister.value.value);
});
</script>

<style lang="scss" scoped>
.register {
  margin: 2px;
  padding: 10px;
  width: 420px;
  font-family: Arial, sans-serif;
  background-color: white;
  border-radius: 5px;
  box-shadow: 0 1px 3px rgba(0.2, 0.2, 0.2, 0.2);
}

.simple-title {
  text-align: center;
}
.simple-title span {
  font-size: 16px;
  color: #409eff;
  font-weight: 500;
}
.simple-title .el-divider {
  margin: 12px 0;
  background-color: #409eff;
}

.form-item {
  width: 400px;
  margin: 5px;
}

.custom-row {
  margin-top: 10px;
  display: flex;
  justify-content: center;
  /* 居中对齐 */
  align-items: center;
  /* 垂直居中（如果需要的话） */
}

.custom-form-item {
  margin: 0 10px;
  /* 左右的间距，根据需要调整 */
}
</style>
